var app = {
	path:{
    	template: '/view/templates/base/template.html',
        scripts: '/js/view/'
    },
    debug: {
        fire: true,
        observed: true,
        observer_error: true,
        bind: true,
        ajax: true,
        template: true,
        script: true
    },
    start: function(){
    	var this_ = this;
    	this.getTemplate(function(success){
            if(success){
	            mlhAPI.main.info({
		            callback:function(data){
		            	if (app.debug.ajax) console.log("Loaded user info");
		                this_.UserInfo = new this_.UserInfoClass(data.data.user_info);
                        mlhAPI.main.shop({
                            mode:"full",
                            callback:function(data){
                                if (app.debug.ajax) console.log("Loaded shop info");
                                this_.ShopInfo = new this_.ShopInfoClass(data.data.shop_info);
        	    				this_.MainView = new this_.MainViewClass();
        	    				if (app.debug.script) console.log("Start");

                                this_.BasketView = new this_.BasketViewClass();
                                this_.ListView = new this_.ListViewClass();
                                this_.ComparisionView = new this_.ComparisionViewClass();

        	    				this_.MainView.render();

                                this_.LeftView = new this_.LeftViewClass();
                                this_.LeftView.setElement('#leftContent');
                                this_.LeftView.render();

                                this_.ContentView = new this_.ContentViewClass();
                                this_.ContentView.setElement('#generalContent');

                                this_.Categories = this_.CategoriesClass.extend({model:this_.CategoryInfoClass});
                                this_.Categories = new this_.Categories(this_.ShopInfo.get('categories'));
                                this_.CategoriesView = new this_.CategoriesViewClass();

                                this_.Articles = this_.ArticlesClass.extend({model:this_.ArticleInfoClass});
                                this_.Articles = new this_.Articles(this_.ShopInfo.get('articles'));
                                this_.ArticleView = new this_.ArticlesViewClass();

                                this_.Products = this_.ProductsClass.extend({model:this_.ProductInfoClass});
                                this_.Products = new this_.Products();
                                this_.ProductView = new this_.ProductViewClass();

                                this_.OrderView = new this_.OrderViewClass();

                                this_.Main = new this_.MainClass();
                                Backbone.history.start();
                            }
                        });
		            }
		        });
	        }
        })
    },
    templates: [],
    //полушение шаблона
    getTemplate: function(callback) {
    	var file = app.path.template;
        var this_ = this;
        if ($.inArray(file, this.templates) < 0) {
            $.ajax(
                {
                    url: file,
                    dataType: 'text',
                    success: function (templateBody) {
                        this_.templates.push(file);
                        try {
                            $(templateBody.split('<!-- TEMPLATE ')).each(function() {
                                var templateName = this.split('-->')[0];
                                var templateText = this.substr(templateName.length + 3);
                                $.template($.trim(templateName), $.trim(templateText));
                            });
                            if (app.debug.template) console.log("Loaded " + file);
                            var success = true;
                        } catch (e) {
                            if (app.debug.template)console.log("Can't parse " + file + "\n" + e.message);
                            success = false;
                        }
                        if (typeof(callback) === 'function') {
                            callback(success);
                        }
                    },
                    error: function() {
                        if (app.debug.template) console.log("Can't load " + file);
                        callback(false);
                    }
                }
            );
        } else {
            if (app.debug.template) console.log("Get template " + file + " from cache");
            callback(true);
        }
    },
    //загрузка скрипта
    loadScript: function(name){
        var file = app.path.scripts + name + '.js';
        var this_ = this;
        var result = false;
        $.ajax(
            {
                url: file,
                async: false,
                dataType: 'script',
                success: function (templateBody) {
                    if (app.debug.script) console.log("Loaded script " + name);
                    result = true;
                },
                error: function() {
                    if (app.debug.script) console.log("Can't load script " + name);
                    result = false;
                }
            }
        );
        return result;
    },
    productCheck:{
        list: [],
        callback: false,
        check: function(){
            if(!this.list.length) {
                this.callback();
                return;
            }
            var this_ = this;
            var id = this.list.pop();
            console.log(id);
            var product = app.Products.get(id);
            if(product && undefined != product.get('params')){
                this_.check();
                return;
            }
            app.Products.getProduct(id,function(){
                this_.check();
            });
        },
        init: function(list,callback){
            if(undefined == list['length']){
                var tmp = [];
                for(var k in list) tmp.push(k.split('_')[1]);
                list = tmp;
            }
            this.list = list;
            this.callback = callback;
            this.check();
        }
    },
    decorate: {
        breadcrumb:[],
        breadcrumbAdd: function(title,link){
            this.breadcrumb.push({
                title:title,
                href:link
            });
            return this;
        },
        breadcrumbRender: function(){
            $('#breadcrumb').html('')
            if(!this.breadcrumb.length) this.breadcrumbAdd('&nbsp;'); 
            $(this.breadcrumb).each(function(){
                $('#breadcrumb').append($.tmpl('breadcrumb_element',this));
            });
            this.breadcrumb = [];
        },
        modalContainer: function(){ 
            return $('#helpWindow');
        },
        image: function(options){
            options = $.extend({
                type: 'info',
                title: 'Картинка',
                img: '',
                delay: 0
            },options);
            var this_ = this;
            $.tmpl('modal_image', options).appendTo(this.modalContainer().html(''));
            this.modalContainer().modal('show');
            if(options['delay']){
                setTimeout(function(){
                    this_.modalContainer().modal('hide');
                },options['delay']);
            }
        },
        imageGallery: function(element,list,first,options){
            var el = [];
            var this_ = this;
            $(list).each(function(){
                el[this.image_id] = $('<img>').attr('src','/data/100_100/' + this.filename)
                    .attr('class',(this.image_id == first ? 'big_image' : 'small_image'))
                    .attr('data-href','/data/origin/' + this.filename)
                    .click(function(){
                        var el = $(this);
                        if(el.hasClass('small_image_container')) el = el.find('img:first');
                        if(el.hasClass('small_image')){
                            var big = el.parents('.image_gallery_box').find('.big_image:first');
                            big.css({height: 'auto',width:'auto'});
                            var tmp = big.attr('data-href');
                            big.attr('data-href',el.attr('src'));
                            el.attr('src',tmp);
                            tmp = big.attr('src');
                            big.attr('src',el.attr('data-href'));
                            el.attr('data-href',tmp);
                        }
                    });
            });
            if(el[first]){
                var tmp = el[first].attr('src');
                el[first].attr('src', el[first].attr('data-href'));
                el[first].attr('data-href', tmp)
                    .addClass('img-rounded')
                    .click(function(){
                        this_.image({
                            img: $(this).attr('src'),
                        })
                    })
                    .load(function(){
                        var el = $(this);
                        var parent = el.parents('.image_gallery_box');
                        if(el.width() >= el.height()){
                            parent.addClass('hor');
                            if(el.width()<parent.width()){
                                el.css('width',450);
                            }
                        } else {
                            parent.removeClass('hor');
                            if(el.height()<parent.height()){
                                if(el.width()*(438/el.height()) > 450){
                                    el.css('width',450);
                                }else{
                                    el.css('height',438);
                                }
                            }
                        }
                    });
                element.append($('<div>').attr('class','big_image_container')
                    .append(el[first])
                )
            }
            for(var k in el){
                if(isNaN(k))break;
                if(k == first) continue;
                element.append(
                    $('<div>').attr('class','small_image_container img-rounded')
                        .append(el[k])
                );
            }
            element.append($('<div>').attr('class','clearfix'));
        },
        showContentLoader: function(){
            $('#contentLoading').show();
        },
        hideContentLoader: function(){
            $('#contentLoading').hide();
        },
        commentsList: function(id,comments,model){
            $('#commentsBlock').remove();
            app.ContentView.add('comment_list',{
                commentsCount:comments.length,
                product_id: id
            });
            if(comments.length){
                $('#commentsList').html($.tmpl('comment_list_element', comments));
                $('#showComments').click(function(){
                    $('#commentsList').toggle();
                });
            }
            var this_ = this;
            this.hideContentLoader();
            $('#comment_reply_block a.btn').click(function(){
                var el = $(this);
                var text = $(this).parent().find('textarea:first').val();
                if(el.hasClass('disabled') || !text) return;
                var id = $(this).data('id');
                this_.showContentLoader();
                el.addClass('disabled');
                mlhAPI[model].setComment({
                    parent_id: 0,
                    model_id: id,
                    description: text,
                    callback: function(result){
                        this_.hideContentLoader();
                        el.removeClass('disabled');
                        if(result['result'] == 'success'){
                            if(result.data['error'])alert(result.data['error']);
                            else {
                                if(model == 'product'){
                                    app.ProductView.showProductComments(app.Products.get(id).set('comments',false));
                                }else{
                                    app.ArticleView.showArticleComments(app.Articles.get(id).set('comments',false));
                                }
                            }
                        }
                    }
                });
            });
        }
    },
    //Главный роутер
    Main: false,
	MainClass: Backbone.Router.extend({
		routes:{
            "" : 'first',
            "!main" : 'main',
            "!article/:id" : "article",
            "!product/:id" : "product",
            "!categories" : "categories",
            "!categories/:model" : "categories",
            "!category/:id" : "category",
            "!tag/:id" : "tag",
            "!comparision" : "comparision",
            "!order" : "order",
            "!order/shiping" : "orderShiping",
            "!order/paying" : "orderPaying",
            "!order/resume" : "orderResume",
            "!order/show/:id" : "orderShow",
            "!order/list": "orderList"
        },
        first: function(){
            this.navigate("!main", true);
        },
        main: function(){
            console.log('main');
            app.ContentView.show('main',{
                shop: app.ShopInfo.attributes
            });
            app.decorate.breadcrumbAdd("Категории продуктов", '#!categories/product')
                .breadcrumbAdd("Новые продукты")
                .breadcrumbRender();
            this.newProducts();
        },
        article: function(id){
            console.log('article',id);
            var articleInfo = app.Articles.get(id);
            var currentCategory = app.Categories.get(articleInfo.get('category_id'));
            app.decorate.breadcrumbAdd("Категории статей", '#!categories/article')
                .breadcrumbAdd(currentCategory.get('title'),'#!category/'+currentCategory.id)
                .breadcrumbAdd(articleInfo.get('title'))
                .breadcrumbRender();
            articleInfo.set('category_title',currentCategory.get('title'));
            app.ContentView.show('article',articleInfo);
            app.ArticleView.showArticleComments(articleInfo);
        },
        product: function(id){
            console.log('product',id);
            app.decorate.showContentLoader();
            app.Products.getProduct(id,function(productInfo){
                var currentCategory = app.Categories.get(productInfo.get('category_id'));
                app.decorate.breadcrumbAdd("Категории продуктов", '#!categories/product')
                    .breadcrumbAdd(currentCategory.get('title'),'#!category/'+currentCategory.id)
                    .breadcrumbAdd(productInfo.get('title'))
                    .breadcrumbRender();
                productInfo.set('currency_name', app.ShopInfo.get('currency_name'));
                app.ContentView.show('product',productInfo.attributes);
                app.ProductView.showProduct(productInfo);
            });
        },
        categories: function(model){
            console.log('categories');
            app.decorate.breadcrumbRender();
            app.CategoriesView.showList(model || 'product');
        },
        category: function(id){
            console.log('category',id);
            var currentCategory = app.Categories.get(id);
            app.decorate.breadcrumbAdd("Категории "+(currentCategory.get('model') == 'product' ? " продуктов" : " статей"), '#!categories/'+currentCategory.get('model'))
                .breadcrumbAdd(currentCategory.get('title'))
                .breadcrumbRender();
            app.ContentView.show('category', currentCategory);
            if(currentCategory.get('model') == 'product'){
                app.ProductView.showProductsByCategory(id);
            }else{
                app.ArticleView.showArticlesByCategory(id);
            }
        },
        tag: function(id){
            console.log('tag',id);
            app.ProductView.showProductsByTag(id);
        },
        newProducts: function(){
            app.ProductView.showControls();
            app.ProductView.showLastProducts();
        },
        comparision: function(){
            app.ComparisionView.show();
        },
        order: function(){
            app.OrderView.show();
        },
        orderShiping: function(){
            app.OrderView.shiping();
        },
        orderPaying: function(){
            app.OrderView.paying();
        },
        orderResume: function(){
            app.OrderView.resume();
        },
        orderShow: function(id){
            app.OrderView.showOrder(id);
        },
        orderList: function(){
            app.OrderView.orderList();
        }

	}),
	//Главная въюха
	MainView: false,
	MainViewClass: Backbone.View.extend({
        events:{
            "click a.basketButton" : "showBasket",
            "click a.listButton" : "showList"
        },
		el: 'body',
		dataHelper: false,
        showBasket: function(){
            app.BasketView.show();
        },
        showList: function(){
            app.ListView.show();
        },
		render: function(){
			this.dataHelper = {
				user: app.UserInfo.attributes,
                shop: app.ShopInfo.attributes,
                basketCount: app.BasketView.getCount(),
                listCount: app.ListView.getCount(),
                comparisionCount: app.ComparisionView.getCount()
			}
			$.tmpl('header',this.dataHelper).prependTo(this.$el);
			return this;
		}
	}),
    //Левая въюха
    LeftView: false,
    LeftViewClass: Backbone.View.extend({
        dataHelper: false,
        events: {
            "click li a" : "select"
        },
        render: function(){
            this.dataHelper = {
                user: app.UserInfo.attributes,
                shop: app.ShopInfo.attributes
            }
            this.$el.html($.tmpl('left',this.dataHelper));
            return this;
        },
        select: function(event){
            this.$el.find('li.active').removeClass('active');
            $(event.currentTarget).parent().addClass('active');
        }
    }),
    //Центральная въюха
    ContentView: false,
    ContentViewClass: Backbone.View.extend({
        template: false,
        data: false,
        show: function(template, data){
            this.template = template;
            this.data = data;
            return this.render();
        },
        render: function(){
            if(this.template){
                this.$el.html($.tmpl(this.template,this.data));
            }
            return this;
        },
        add: function(template, data){
            if(template){
                this.$el.append($.tmpl(template,data));
            }
            return this;
        }
    }),
    BasketView: false,
    BasketViewClass: Backbone.View.extend({
        events:{
            "click a.deleteFromBasket" : "deleteFromBasket",
            "click a.orderButton" : "hide"
        },
        template: 'basket_list',
        show: function(){
            var this_ = this;
            app.productCheck.init(window.localStorage['basketCount'] ? JSON.parse(window.localStorage['basket']) : [], function(){
                this_.render();
                this_.$el.modal('show');
            });
        },
        render: function(){
            var basket = app.Products.where({inBasket:true});
            app.decorate.modalContainer().html('').append($.tmpl(this.template, {
                basketCount: basket.length,
                basket:basket
            }));
            this.setElement(app.decorate.modalContainer());
            return this;
        },
        remove: function(id){
            app.Products.get(id).set('inBasket',false);
            var basket = app.Products.where({inBasket:true});
            if(basket.length){
                $('#basketEmpty').hide();
                $('#basketStatus').text(basket.length);
            } else {
                $('#basketEmpty').show();
                $('#basketStatus').text("");
            }
            this.updateLocalStorage();
            return this;
        },
        add: function(id){
            app.Products.get(id).set('inBasket',true);
            var basket = app.Products.where({inBasket:true});
            $('#basketEmpty').hide();
            $('#basketStatus').text(basket.length);
            this.updateLocalStorage();
            return this;
        },
        deleteFromBasket: function(event){
            var id = $(event.currentTarget).data('id');
            console.log('Remove from basket', id);
            this.remove(id)
                .render();
            $('.basket[data-id='+id+'] a.btn-success').each(function(){
                $(this).removeClass('btn-success')
                    .addClass('btn-primary')
                    .find('.icon-white')
                        .attr('class','icon-white icon-shopping-cart')
                        .next().text('В корзину');
            });
        }, 
        updateLocalStorage: function(){
            var data = {};
            var count = 0;
            $(app.Products.where({inBasket:true})).each(function(){
                data['p_'+this.get('product_id')] = {
                    basket: 1
                };
                count++;
            });
            window.localStorage['basket'] = JSON.stringify(data);
            window.localStorage['basketCount'] = count;
        },
        getCount: function(){
            return window.localStorage['basketCount'] ? window.localStorage['basketCount']*1 : 0;
        },
        hide: function(){
            app.decorate.modalContainer().modal('hide');
        }
    }),
    ListView: false,
    ListViewClass: Backbone.View.extend({
        events:{
            "click a.deleteFromList" : "deleteFromList",
            "click .byeButton": "addToBasket",
            "click .addToComparision": "addToComparision"
        },
        template: 'list_list',
        show: function(){
            var this_ = this;
            app.productCheck.init(window.localStorage['listCount'] ? JSON.parse(window.localStorage['list']) : [], function(){
                this_.render();
                this_.$el.modal('show');
            });
        },
        render: function(){
            var list = app.Products.where({inList:true});
            app.decorate.modalContainer().html('').append($.tmpl(this.template, {
                listCount: list.length,
                list:list
            }));
            this.setElement(app.decorate.modalContainer());
            return this;
        },
        remove: function(id){
            app.Products.get(id).set('inList',false);
            var list = app.Products.where({inList:true});
            if(list.length){
                $('#listLink').show();
                $('#listStatus').text(list.length);
            } else {
                $('#listLink').hide();
                $('#listStatus').text("");
            }
            this.updateLocalStorage();
            return this;
        },
        add: function(id){
            app.Products.get(id).set('inList',true);
            var list = app.Products.where({inList:true});
            $('#listLink').show();
            $('#listStatus').text(list.length);
            this.updateLocalStorage();
            return this;
        },
        deleteFromList: function(event){
            var id = $(event.currentTarget).data('id');
            console.log('Remove from list', id);
            this.remove(id)
                .render();
            $('li.disabled .addToList[data-id='+id+']').each(function(){
                $(this).parent().removeClass('disabled');
            });
        }, 
        updateLocalStorage: function(){
            var data = {};
            var count = 0;
            $(app.Products.where({inList:true})).each(function(){
                data['p_'+this.get('product_id')] = {
                    list: 1
                };
                count++;
            });
            window.localStorage['list'] = JSON.stringify(data);
            window.localStorage['listCount'] = count;
        },
        getCount: function(){
            return window.localStorage['listCount'] ? window.localStorage['listCount']*1 : 0;
        },
        addToBasket: function(event){
            app.ProductView.addToBasket(event);
        },
        addToComparision: function(event){
            app.ProductView.addToComparision(event);
        }
    }),
    ComparisionView: false,
    ComparisionViewClass: Backbone.View.extend({
        events:{
            "click a.deleteFromComparision" : "deleteFromComparision",
            "click .byeButton": "addToBasket",
            "click .addToList": "addToList",
            "click .onlyDiff" : "onlyDiff"
        },
        template: 'comparision_list',
        diffMode: false,
        show: function(){
            var this_ = this;
            app.ContentView.show('comparision');
            app.decorate.showContentLoader();
            app.productCheck.init(window.localStorage['comparisionCount'] ? JSON.parse(window.localStorage['comparision']) : [], function(){
                this_.render();
            });
        },
        render: function(){
            $('#comparisionList').remove();
            var comparision = app.Products.where({inComparision:true});
            var comparisionList = new Backbone.Collection();
            $(comparision).each(function(){
                $(this.get('params')).each(function(){
                    if(this.type>4 && this.type !=6) return;
                    comparisionList.add({
                        id: this.param_id,
                        title: this.title,
                        description: this.description,
                        values: this.values,
                        type: this.type,
                        data:{},
                        comparision: comparision
                    });
                });
                $(this.get('param_data')).each(function(){
                    var param = comparisionList.get(this.param_id);
                    if(!param) return;
                    param.attributes.data['p_'+this.product_id] = this.small_value || this.long_value;
                });
            });
            $(comparision).each(function(){
                var id = this.id;
                $(comparisionList.models).each(function(){
                    if(this.get('data')['p_'+id] == undefined){
                        this.attributes.data['p_'+id] = null;
                    }
                });
            });
            this.setElement('#productContent');
            this.$el.append($.tmpl(this.template, {
                comparisionCount: this.getCount(),
                comparisionList: comparisionList.models,
                comparision: comparision
            }));
            var this_ = this;
            $(comparisionList.models).each(function(){
                var id = this.id;
                var type = this.get('type');
                var found = false;
                var dif = false;
                var pre = [];
                var data = this.get('data');
                for(var k in data){
                    if(pre.length && $.inArray(data[k],pre)<0) dif = true;
                    pre.push(data[k]);
                    if(data[k] || type == 6){
                        found = true;
                        if(type == 6){
                            $('#pa_'+id+' span[data-id='+k+']').html('<i class="icon icon-'+(data[k] ? 'ok' : 'remove')+'"></i>');
                        } else {
                            $('#pa_'+id+' span[data-id='+k+']').text(data[k]).attr('title',type);
                        }
                    }
                };
                if(!found && type!=6){
                    $('#pa_'+id).remove();
                }else{
                    $('#pa_'+id).show().addClass(dif?'':'dif');
                }
            });
            app.decorate.hideContentLoader();
            return this;
        },
        remove: function(id){
            app.Products.get(id).set('inComparision',false);
            var comparision = app.Products.where({inComparision:true});
            if(comparision.length){
                $('#comparisionLink').show();
                $('#comparisionStatus').text(comparision.length);
            } else {
                $('#comparisionLink').hide();
                $('#comparisionStatus').text("");
            }
            this.updateLocalStorage();
            return this;
        },
        add: function(id){
            app.Products.get(id).set('inComparision',true);
            var comparision = app.Products.where({inComparision:true});
            $('#comparisionLink').show();
            $('#comparisionStatus').text(comparision.length);
            this.updateLocalStorage();
            return this;
        },
        deleteFromComparision: function(event){
            var id = $(event.currentTarget).data('id');
            console.log('Remove from comparision', id);
            this.remove(id)
                .render();
            $('li.disabled .addToComparision[data-id='+id+']').each(function(){
                $(this).parent().removeClass('disabled');
            });
        }, 
        updateLocalStorage: function(){
            var data = [];
            $(app.Products.where({inComparision:true})).each(function(){
                data.push(this.get('product_id'));
            });
            window.localStorage['comparision'] = JSON.stringify(data);
            window.localStorage['comparisionCount'] = data.length;
        },
        getCount: function(){
            return window.localStorage['comparisionCount'] ? window.localStorage['comparisionCount']*1 : 0;
        },
        addToBasket: function(event){
            app.ProductView.addToBasket(event);
        },
        addToList: function(event){
            app.ProductView.addToList(event);
        },
        onlyDiff: function(){
            this.diffMode = !this.diffMode;
            this.$el.find('.dif')[this.diffMode ? 'hide' : 'show']('fast');
        }
    }),
    OrderView: false,
    OrderViewClass: Backbone.View.extend({
        events:{
            'keyup input.elementCount': 'recalculate',
            "click a.deleteFromBasket" : "deleteFromBasket",
            "click input[name=orderShipingType]" : "selectShiping",
            "click input[name=orderPayingType]" : "selectPaying"
        },
        shipingList:false,
        paymentList:false,
        success: false,
        data:{
            basket:false,
            totallCount:0,
            totallPrice:0,
            shiping: 0,
            payMethod: 0,
            comment: false,
            currencyName: "",
            address: false,
        },
        show: function(){
            var this_ = this;
            app.ContentView.show('order');
            $('#orderStep').html('Просмотр товаров');
            app.decorate.showContentLoader();
            app.productCheck.init(window.localStorage['basketCount'] ? JSON.parse(window.localStorage['basket']) : [], function(){
                var order = app.Products.where({inBasket:true});
                this_.render('order_list',{
                    orderCount: order.length,
                    order:order
                });
                this_.recalculate();
                app.decorate.hideContentLoader();
            });
        },
        shiping: function(){
            if(!this.data.basket){
                app.Main.navigate('!order',true);
                return;
            }
            var this_ = this;
            var haveAddress = false;
            var disp = function(){
                this_.data.shiping = this_.data.shiping || this_.shipingList[0].name;
                $(this_.shipingList).each(function(){
                    this['checked'] = this.name == this_.data.shiping;
                });
                this_.render('order_shiping',{
                    data: this_.data.address,
                    shiping: this_.data.shiping,
                    shipingList: this_.shipingList,
                    haveAddress:haveAddress,
                    userInfo: app.UserInfo.attributes
                });
                $('#orderStep').html('Выбор способа доставки');
                $('#orderContent input[name=orderShipingAddress]').click(function(){
                    if($('#orderContent input[name=orderShipingAddress]:checked').val() == 1){
                        $('.addressInfo').hide();
                        $('.form-horizontal .controls>input').show();
                        this_.data.address = {};
                    }else{
                        $('.form-horizontal .controls>input').hide();
                        $('.addressInfo').show();
                        this_.data.address = 1;
                    }
                });
                $('#orderContent div[data-type=addressSelectType] input[value='+(this_.data.address == 1 ? '0' : '1')+']').click();
            }
            var getMethods = function(){
                if(this_.shipingList){
                    disp();
                }else{
                    mlhAPI.order.shipMethods({
                        callback: function(data){
                            console.log('Ship methods', data);
                            if(data.result == 'success'){
                                this_.shipingList = data.data.info;
                            }
                            disp();
                        }
                    })
                }
            }
            if(undefined == app.UserInfo.get('address') && this_.data.address == false){
                mlhAPI.user.getAddress({
                    id: app.UserInfo.get('user_id'),
                    callback: function(data){
                        console.log('User address', data);
                        if(data.result == 'success'){
                            var info = data.data.info;
                            haveAddress = true;
                            app.UserInfo.set('user_city',info.city);
                            app.UserInfo.set('user_country',info.country);
                            app.UserInfo.set('user_tel',info.tel);
                            app.UserInfo.set('user_address',info.address);
                            this_.data.address = 1;
                        }
                        getMethods();
                    }
                })
            }else{
                haveAddress = true;
                if(this_.data.address == false){
                    this_.data.address = 1;
                }
                getMethods();
            }
        },
        paying: function(){
            if(!this.data.basket){
                app.Main.navigate('!order',true);
                return;
            }
            if(!this.data.shiping){
                app.Main.navigate('!order/shiping',true);
                return;
            }
            if(this.data.address!=1){
                var this_ = this;
                $('.form-horizontal .controls>input').each(function(){
                    this_.data.address[this.id.split('input')[1]] = this.value;
                });
            }
            var this_ = this;
            var disp = function(){
                this_.data.payMethod = this_.data.payMethod || this_.paymentList[0].name;
                $(this_.paymentList).each(function(){
                    this['checked'] = this.name == this_.data.payMethod;
                });
                this_.render('order_paying',{
                    data:this_.data,
                    payMethod: this_.paymentList
                });
            }
            if(this.paymentList){
                    disp();
                }else{
                    mlhAPI.order.paymentMethods({
                        callback: function(data){
                            console.log('Payment methods', data);
                            if(data.result == 'success'){
                                this_.paymentList = data.data.info;
                            }
                            disp();
                        }
                    })
                }
            $('#orderStep').html('Выбор способа оплаты');
        },
        resume: function(){
            if(!this.data.basket){
                app.Main.navigate('!order',true);
                return;
            }
            if(!this.data.shiping){
                app.Main.navigate('!order/shiping',true);
                return;
            }
            if(!this.data.payMethod){
                app.Main.navigate('!order/paying',true);
                return;
            }
            this.data.comment = $('#orderComment').val();
            app.ContentView.show('order');
            app.decorate.hideContentLoader();
            $('#orderStep').html('Просмотр заказа');
            var findMethod = function(name, list){
                for (var i = 0; i < list.length; i++) {
                    if(list[i].name == name) return list[i];
                };
                return 0;
            }
            var order = app.Products.where({inBasket:true});
            var this_ = this;
            this.render('order_resume',{
                orderCount: order.length,
                order:order,
                data:this.data,
                userInfo: app.UserInfo.attributes,
                shipingInfo: findMethod(this.data.shiping, this.shipingList),
                payInfo: findMethod(this.data.payMethod, this.paymentList)
            });
            $('#totallCount').text(this.data.totallCount);
            $('#totallPrice').text(this.data.totallPrice+" "+(this.data.currencyName || ''));
            $('#buyButton').click(function(){
                if(this_.data.address == 1){
                    this_.data.address = {
                            'City': app.UserInfo.get('user_city'),
                            'Country': app.UserInfo.get('user_country'),
                            'Tel': app.UserInfo.get('user_tel'),
                            'Address': app.UserInfo.get('user_address'),
                            'Name': app.UserInfo.get('user_name')
                    };
                }
                var basket = [];
                for(var k in this_.data.basket){
                    basket.push({
                        product_id: k.split('_')[1],
                        count: this_.data.basket[k]
                    })
                }
                mlhAPI.order.new({
                    order: {
                        basket: basket,
                        address: this_.data.address,
                        comment: this_.data.comment,
                        shiping: this_.data.shiping,
                        payMethod: this_.data.payMethod
                    },
                    callback: function(data){
                        if(data.data.result == 'ok'){
                            this_.success = true;
                            app.Main.navigate('!order/show/'+data.data.id+'/success',true);
                        }
                    }
                });
            });
        },
        showOrder: function(id){
            app.ContentView.show('order_show',{
                id:id,
                success: this.success
            });
            this.success = false;
            app.decorate.breadcrumbAdd("Ваши заказы", '#!order/list')
                .breadcrumbAdd("Заказ №"+id)
                .breadcrumbRender();
            mlhAPI.order.get({
                id: id,
                callback:function(data){
                    var totall_price = 0;
                    var totall_count = 0;
                    $(data.data.element.orderList).each(function(){
                        this['currency'] = data.data.currency
                        totall_price += this['totallPrice']*1;
                        totall_count += this['product_count']*1;
                    });

                    console.log(data);
                    app.ContentView.add('order_show_info',{
                        currencyData: data.data.currency,
                        data: data.data.element,
                        totall_price: totall_price,
                        totall_count: totall_count
                    });
                }
            })
        },

        orderList: function(){
            app.decorate.breadcrumbRender();
            app.ContentView.show('order_list');
            mlhAPI.order.getList({
                shop: app.ShopInfo.get('name'),
                callback: function(data){
                    console.log(data);
                    app.ContentView.add('order_list_element',data.data.list);
                }
            });
        },
        render: function(template, data){
            $('#orderContent').remove();
            app.ContentView.add(template, data);
            this.setElement('#orderContent');
            return this;
        },
        recalculate: function(){
            var count = 0;
            var price = 0;
            var currencyName = "";
            var basket = {};
            this.$el.find('input.elementCount').each(function(){
                var el = $(this);
                var id = el.data('id');
                var product = app.Products.get(id);
                var val = el.val()*1;
                if(isNaN(val) || !val) return;
                val = Math.floor(Math.abs(val));
                count+=val;
                price+=product.get('price')*val;
                if(!currencyName || undefined == currencyName)currencyName = product.get('currency_name');
                basket['p_'+id]=val;
            });
            this.data.basket = basket;
            this.data.totallCount = count;
            this.data.totallPrice = price;
            this.data.currencyName = currencyName;
            $('#totallCount').text(count);
            $('#totallPrice').text(price+" "+(currencyName || ''));
        },
        deleteFromBasket:function(event){
            app.BasketView.deleteFromBasket(event);
            $(event.currentTarget).parent().parent().parent().remove();
            this.recalculate();
        },
        selectShiping: function(event){
            this.data.shiping = $(event.currentTarget).val();
        },
        selectPaying: function(event){
            this.data.payMethod = $(event.currentTarget).val();
        }
    }),
    //Въюха для продуктов
    ProductView: false,
    ProductViewClass: Backbone.View.extend({
        productShowMode: 'big',
        template: false,
        data: false,
        events: {
            "click .selectProductType":          "changeShowProductType",
            "click .byeButton": "addToBasket",
            "click .addToList": "addToList",
            "click .addToComparision": "addToComparision"
        },
        showControls: function(template, data){
            if(!$('#productContent').length){
                app.ContentView.add('product_controll');
                this.setElement('#productContent');
            }
            this.$el.find('#productList').html($.tmpl(this.productShowMode + '_product_list'));
            app.decorate.showContentLoader();
        },
        render: function(){
            if(this.template){
                this.$el.find('#productList *:first').html($.tmpl(this.template,this.data));
            }
            app.decorate.hideContentLoader();
            return this;
        },
        showLastProducts:function(){
            var this_ = this;
            app.Products.getLastProducts(function(){
                this_.data = app.Products.where({
                    isNew:true
                });
                this_.template = this_.productShowMode + '_product_list_element';
                this_.render();
            });
        },
        showProductsByCategory:function(id){
            var this_ = this;
            this.showControls();
            app.Products.getProductsByCategory(function(){
                this_.data = app.Products.where({
                    category_id: id
                });
                this_.template = this_.productShowMode + '_product_list_element';
                this_.render();
            },id);
        },
        showProductsByTag:function(id){
            var this_ = this;
            app.Products.getProductsByTag(function(data){
                this_.data = [];
                var tagName = "";
                $(data).each(function(){
                    this_.data.push(app.Products.get(this.product_id));
                    if(!tagName){
                        tagName = " ";
                        $(this_.data[0].get('tags')).each(function(){
                            if(this.tag_id == id) tagName = this.tag_title;
                        });
                    }
                });
                app.ContentView.show('tag',{tagName:tagName});
                this_.showControls();
                this_.template = this_.productShowMode + '_product_list_element';
                this_.render();
            },id);
        },
        changeShowProductType: function(el){
            var newShowProductMode = $(el.currentTarget).data('type');
            if(newShowProductMode == this.productShowMode) return;
            this.productShowMode = newShowProductMode;
            this.template = this.productShowMode + '_product_list_element';
            this.showControls();
            this.render();
        },
        showProduct: function(productInfo){
            var this_ = this;
            this.setElement('#productContent');
            app.decorate.imageGallery(this.$el.find('[rel=productImages]'),productInfo.get('image'),productInfo.get('image_id'));
            this.showProductComments(productInfo);
        },
        showProductComments: function(productInfo){
            var this_ = this;
            productInfo.getComments(function(comments){
                app.decorate.commentsList(productInfo.get('product_id'),comments,'product');
            });
        },
        addToBasket: function(event){
            var id = $(event.currentTarget).parent().data('id');
            console.log('Add to basket', id);
            if($(event.currentTarget).hasClass('btn-primary')){
                $('.basket[data-id='+id+'] .btn-primary').removeClass('btn-primary')
                    .addClass('btn-success')
                    .find('.icon-white')
                        .attr('class','icon-white icon-ok')
                        .next().text('Оформить');
                app.BasketView.add(id);
            }else{
                app.Main.navigate('!order',true);                
            }
        },
        addToList: function(event){
            var id = $(event.currentTarget).data('id');
            console.log('Add to list', id);
            if(!$(event.currentTarget).parent().hasClass('disabled')){
                $(event.currentTarget).parent().addClass('disabled');
                app.ListView.add(id);
            }
        },
        addToComparision: function(event){
            var id = $(event.currentTarget).data('id');
            console.log('Add to comparision', id);
            if(!$(event.currentTarget).parent().hasClass('disabled')){
                $(event.currentTarget).parent().addClass('disabled');
                app.ComparisionView.add(id);
            }
        }
    }),
	//Информация о пользователе
	UserInfo: false,
	UserInfoClass:      Backbone.Model.extend({}),
    //Информация о магазине
    ShopInfo: false,
    ShopInfoClass:      Backbone.Model.extend({}),
    //Категории магазина
    Categories: false,
    CategoryInfoClass:  Backbone.Model.extend({
        idAttribute: "category_id"
    }),
    CategoriesClass:    Backbone.Collection.extend({}),
    CategoriesView: false,
    CategoriesViewClass: Backbone.View.extend({
        showList: function(model){
            app.ContentView.show('categories_list',{
                model: model,
                categories: model ? app.Categories.where({model:model}) : app.Categories.models
            });
        }
    }),
    //Статьи для магазина
    
    Articles: false,
    ArticleInfoClass:   Backbone.Model.extend({
        idAttribute: "article_id",
        initialize: function(){
            this.set('comments',false);
        },
        getComments: function(callback){
            if(this.get('comments') !== false) {
                if(callback)callback(this.get('comments'));
                return;
            } 
            var this_ = this;
            mlhAPI.article.getComments({
                id: this.id,
                requestType:'get_rc',
                callback: function(data){
                    var comments = [];
                    var c = 0;
                    var comment = data.data[c];
                    if(comment){
                        while(comment){
                            comments.push(comment);
                            comment = data.data[++c];
                        }
                    }
                    this_.set('comments',comments);
                    console.log(comments);
                    if(callback)callback(comments);
                }
            });
        }
    }),
    ArticlesClass:      Backbone.Collection.extend({}),
    ArticlesView: false,
    ArticlesViewClass: Backbone.View.extend({
        data: false,
        template: false,
        render: function(){
            if(!$('#articleList').length){
                app.ContentView.add('articles_list');
                this.setElement('#articleList');
            }
            if(this.template){
                this.$el.find('*:first').html($.tmpl(this.template,this.data));
            }
            app.decorate.hideContentLoader();
            return this;
        },
        showArticlesByCategory: function(id){
            this.data = app.Articles.where({
                category_id: id
            })
            this.template = 'articles_list_element';
            this.render();
        },
        showArticleComments: function(articleInfo){
            var this_ = this;
            articleInfo.getComments(function(comments){
                app.decorate.commentsList(articleInfo.get('article_id'),comments,'article');
            });
        }
    }),
    //Товары для магазина
    Products: false,
    ProductInfoClass:   Backbone.Model.extend({
        idAttribute: "product_id",
        initialize: function(){
            var localBasket = window.localStorage['basket'];
            if(localBasket){
                localBasket = JSON.parse(localBasket);
                this.set('inBasket',localBasket['p_'+this.get('product_id')] != undefined);
            }
            var localList = window.localStorage['list'];
            if(localList){
                localList = JSON.parse(localList);
                this.set('inList',localList['p_'+this.get('product_id')] != undefined);
            }
            var localComparision = window.localStorage['comparision'];
            if(localComparision){
                localComparision = JSON.parse(localComparision);
                this.set('inComparision', $.inArray(this.get('product_id'), localComparision)>-1);
            }
            this.set('comments',false);

        },
        getComments: function(callback){
            if(this.get('comments') !== false) {
                if(callback)callback(this.get('comments'));
                return;
            } 
            var this_ = this;
            mlhAPI.product.getComments({
                id: this.id,
                requestType:'get_rc',
                callback: function(data){
                    var comments = [];
                    var c = 0;
                    var comment = data.data[c];
                    if(comment){
                        while(comment){
                            comments.push(comment);
                            comment = data.data[++c];
                        }
                    }
                    this_.set('comments',comments);
                    console.log(comments);
                    if(callback)callback(comments);
                }
            });
        }
    }),
    ProductsClass:      Backbone.Collection.extend({
        haveLast: false,
        getProduct: function(id,callback){
            var product = this.get(id);
            if(product && undefined != product.get('params')){
                callback(product);
                return;
            }
            var this_ = this;
            mlhAPI.product.get({
                id: id,
                callback: function(data){
                    var paramsData = [];
                    $(data.data.element.param_data).each(function(){
                        paramsData[this.param_id] = this.small_value || this.long_value;
                    });
                    var extendFunctions = {
                        getTPL: function(type){
                            return 'param_show_field_type_' + type;
                        },
                        list: function(list){
                            var ret = [];
                            $(list.split(',')).each(function(){
                                ret.push($.trim(this));
                            });
                            return ret;
                        }
                    };
                    $(data.data.element.params).each(function(){
                        this['currentValue'] = paramsData[this.param_id];
                        this['getTPL'] = extendFunctions.getTPL;
                        this['list'] = extendFunctions.list;
                    });
                    data.data.element['tags_count'] = data.data.element.tags.length;
                    console.log(data.data.element);
                    this_.add(data.data.element,{merge : true});
                    console.log(data);
                    callback(this_.get(id));
                }
            });
        },
        getProductsByCategory: function(callback,category_id){
            var this_ = this;
            var callback = callback;
            mlhAPI.product.get({
                category_id: category_id,
                callback: function(data){
                    $(data.data.element).each(function(){
                        this['currency_name'] = app.ShopInfo.get('currency_name');
                    });
                    this_.add(data.data.element);
                    this_.haveLast = true;
                    console.log(data);
                    callback(data.data.element);
                }
            });
        },
        getProductsByTag: function(callback,tag_id){
            var this_ = this;
            var callback = callback;
            mlhAPI.product.get({
                tag_id: tag_id,
                callback: function(data){
                    $(data.data.element).each(function(){
                        this['currency_name'] = app.ShopInfo.get('currency_name');
                    });
                    this_.add(data.data.element);
                    this_.haveLast = true;
                    console.log(data);
                    callback(data.data.element);
                }
            });
        },
        getLastProducts: function(callback){
            var this_ = this;
            if(this.haveLast) {
                callback();
                return;
            }
            var callback = callback;
            mlhAPI.product.getList({
                order: 'product.created DESC',
                callback: function(data){
                    $(data.data.list).each(function(){
                        this['currency_name'] = app.ShopInfo.get('currency_name');
                        this['isNew'] = true;
                    });
                    this_.add(data.data.list);
                    this_.haveLast = true;
                    console.log(data);
                    callback();
                }
            });
        }
    })
};
$(document).ready(function(){
	_.extend(app, Backbone.Events);
	app.start.call(app);
});